<?php
//+---------------------------------------------------------------------------------------------------------------------
//| 人生是荒芜的旅行，冷暖自知，苦乐在心
//+---------------------------------------------------------------------------------------------------------------------
//| Author:Janmas <janmas@126.com>
//+---------------------------------------------------------------------------------------------------------------------
//| 
//+---------------------------------------------------------------------------------------------------------------------


namespace app\common\command;


use app\admin\exception\LogicException;
use app\common\exception\PluginException;
use think\console\Input;
use think\console\input\Option;
use think\console\Output;

/**
 * 插件安装器
 * @package app\common\command
 */
class Install extends \think\console\Command
{
	protected function configure()
	{
		$this->setName('install')
			->addOption('name',null, Option::VALUE_OPTIONAL, "插件名称")
			->setDescription('安装插件 php think install --name 插件名');
	}

	protected function execute( Input $input, Output $output )
	{
	    $installProgram = (new \app\admin\service\Plugin());
		$name = trim($input->getOption('name'));
		if(!empty($name)){
            /**
             * @var \app\common\plugins\Plugin $plugin;
             */
            $plugin = get_plugin_instance($name);
            if(is_null($plugin)){
                $output->write('插件'.$name.'不存在');
                exit;
            }
            try{
	            $installProgram->install($plugin,true);
	            $output->write('安装成功');
				exit();
            }catch (LogicException $e){
            	if(env('APP_DEBUG')){
            		echo "ErrorInfo:\r\n";
            		echo "错误信息:{$e->getMessage()}\r\n";
            		echo "错误文件:{$e->getFile()}\r\n";
            		echo "错误行号：{$e->getLine()}\r\n";
	            }
            }catch(PluginException $e){
	            if(env('APP_DEBUG')){
		            echo "ErrorInfo:\r\n";
		            echo "错误信息:{$e->getMessage()}\r\n";
		            echo "错误文件:{$e->getFile()}\r\n";
		            echo "错误行号：{$e->getLine()}\r\n";
	            }
            }
            $output->write('安装失败');
            exit;
		}

        $answer = $output->ask($input,'您确定要安装所有的插件？');

		if(strtolower($answer) == 'y' || $answer == 1){
		    $files = glob(app()->getRootPath().'plugins\*',GLOB_MARK );
		    $instances = array_map(function($dir){
                if(substr($dir,-1,1) == '\\' && !is_file($dir.'\\install.lock')){


                    $dirArr = array_filter(explode('\\',$dir));
                    return get_plugin_instance(array_pop($dirArr));
                }
            },$files);
            $instances = array_filter($instances);
            foreach($instances as $instance){
                $installProgram->install($instance,true);
            }
        }
	}
}